﻿using UnityEngine;
using UnityEditor;
using System.Collections.Generic;

namespace MagicLib
{
    [InitializeOnLoad]
    public static class ViewHotbox
    {
        private static bool isHotboxActive;
        private static Vector2 hotboxPosition;
        private static float hotboxRadius = 120f;
        private static float deadZoneRadius = 60f;
        private static List<HotboxRegion> regions = new List<HotboxRegion>();
        private static HotboxRegion currentRegion;
        private static HotboxRegion lastExecutedRegion = HotboxRegion.None;
        private static SceneView activeSceneView;
        private static bool isBackQuoteDown;
        private static Vector2 lastMousePosition;

        // 新增纹理变量
        private static Texture2D centerRingTexture;
        private static Texture2D directionArcTexture;
        private static Texture2D menuBackgroundNormalTexture;
        private static Texture2D menuBackgroundHighlightTexture;

        private enum HotboxRegion
        {
            None,
            Top,
            Bottom,
            Left,
            Right,
            Front,
            Back,
            Toggle2D3D,
            Focus
        }

        static ViewHotbox()
        {
            CreateTextures();
            InitializeRegions();
            SceneView.duringSceneGui += DuringSceneGUI;
        }

        private static void DuringSceneGUI(SceneView sceneView)
        {
            Event e = Event.current;
            activeSceneView = sceneView;

            // 检测单独的~键按下
            if (e.type == EventType.KeyDown && e.keyCode == KeyCode.BackQuote)
            {
                // 忽略组合键
                if (e.control || e.command || e.alt || e.shift) return;
                isBackQuoteDown = true;
                if (isBackQuoteDown && !isHotboxActive)
                {
                    hotboxPosition = e.mousePosition;
                    lastMousePosition = e.mousePosition;
                }

                isHotboxActive = true;
                currentRegion = HotboxRegion.None;
                lastExecutedRegion = HotboxRegion.None;
                SceneView.RepaintAll();
                e.Use();
            }

            // 更新鼠标位置（即使没有事件）
            if (isHotboxActive && e.type != EventType.Repaint)
            {
                lastMousePosition = e.mousePosition;
            }

            // 更新鼠标热盒交互动态
            if (isHotboxActive)
            {
                DrawHotbox(sceneView);
                ProcessInput(sceneView);
            }

            // 检测~键释放
            if (e.type == EventType.KeyUp && e.keyCode == KeyCode.BackQuote)
            {
                // 仅在非死区区域变化时
                if (currentRegion != lastExecutedRegion)
                {
                    ExecuteRegionAction(sceneView);
                    //todo:第二次调用右上角的视图指示文本才会立刻更新
                    ExecuteRegionAction(sceneView);
                    //todo:第三次保证2D3D切换和聚焦功能正常（暂时先这么处理）
                    ExecuteRegionAction(sceneView);
                    lastExecutedRegion = currentRegion;
                }
                isBackQuoteDown = false;
                CloseHotbox();
                e.Use();
            }

            // macOS 特定修复：强制重绘
            if (isHotboxActive && Application.platform == RuntimePlatform.OSXEditor)
            {
                sceneView.Repaint();
                EditorApplication.QueuePlayerLoopUpdate();
            }
        }

        private static void DrawHotbox(SceneView sceneView)
        {
            Handles.BeginGUI();
            GUI.depth = -100; // 确保在最上层渲染

            // 绘制中心指示器
            DrawCenterIndicator();

            // 绘制所有区域标签
            DrawRegionLabels(sceneView);

            // 绘制死区指示器
            DrawDeadZoneIndicator();

            Handles.EndGUI();
        }

        private static void DrawCenterIndicator()
        {
            // 绘制中心圆环
            if (centerRingTexture != null)
            {
                Rect ringRect = new Rect(
                    hotboxPosition.x - deadZoneRadius,
                    hotboxPosition.y - deadZoneRadius,
                    deadZoneRadius * 2,
                    deadZoneRadius * 2
                );
                GUI.DrawTexture(ringRect, centerRingTexture, ScaleMode.ScaleToFit);
            }

            // 绘制方向扇形
            if (directionArcTexture != null)
            {
                // 计算鼠标方向角度
                Vector2 direction = lastMousePosition - hotboxPosition;
                float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;

                // 保存当前GUI矩阵
                Matrix4x4 matrixBackup = GUI.matrix;

                // 围绕热盒中心旋转
                GUIUtility.RotateAroundPivot(angle, hotboxPosition);

                // 绘制扇形
                Rect arcRect = new Rect(
                    hotboxPosition.x - deadZoneRadius,
                    hotboxPosition.y - deadZoneRadius,
                    deadZoneRadius * 2,
                    deadZoneRadius * 2
                );
                GUI.DrawTexture(arcRect, directionArcTexture, ScaleMode.ScaleToFit);

                // 恢复GUI矩阵
                GUI.matrix = matrixBackup;
            }
        }

        private static void DrawRegionLabels(SceneView sceneView)
        {
            foreach (var region in regions)
            {
                DrawRegionLabel(region, sceneView);
            }
        }

        private static void DrawRegionLabel(HotboxRegion region, SceneView sceneView)
        {
            var regionData = GetRegionData(region, sceneView);
            bool isHighlighted = region == currentRegion;
            Vector2 labelPos = hotboxPosition + regionData.direction * hotboxRadius;

            // 使用图标背景
            Texture2D bgTexture = isHighlighted ? menuBackgroundHighlightTexture : menuBackgroundNormalTexture;

            // 标签大小（根据图标尺寸调整）
            float iconSize = 80f;
            Rect bgRect = new Rect(
                labelPos.x - iconSize / 2,
                labelPos.y - iconSize / 2,
                iconSize,
                iconSize
            );

            // 绘制背景图标
            if (bgTexture != null)
            {
                GUI.DrawTexture(bgRect, bgTexture, ScaleMode.ScaleToFit);
            }

            // 优化的标签样式
            GUIStyle labelStyle = new GUIStyle(EditorStyles.whiteLabel);
            labelStyle.normal.textColor = Color.black;
            labelStyle.alignment = TextAnchor.MiddleCenter;
            labelStyle.fontSize = 11;
            labelStyle.fontStyle = FontStyle.Normal;
            labelStyle.padding = new RectOffset(0, 0, 0, 0);
            labelStyle.contentOffset = Vector2.zero; // 修复 macOS 偏移

            // 绘制文字
            GUI.Label(bgRect, regionData.label, labelStyle);
        }

        private static void DrawDeadZoneIndicator()
        {
            // 只保留文字提示
            GUIStyle labelStyle = new GUIStyle(EditorStyles.whiteLabel)
            {
                alignment = TextAnchor.MiddleCenter,
                fontSize = 8,
                normal = { textColor = new Color(0.8f, 0.8f, 0.8f, 0.5f) }
            };

            Rect labelRect = new Rect(
                hotboxPosition.x - 40,
                hotboxPosition.y - 8,
                80, 16
            );

            GUI.Label(labelRect, "MagicLib", labelStyle);
        }

        private static void ProcessInput(SceneView sceneView)
        {
            // 更新当前区域
            UpdateCurrentRegion(lastMousePosition);
        }

        private static void UpdateCurrentRegion(Vector2 mousePosition)
        {
            Vector2 direction = mousePosition - hotboxPosition;
            float distance = direction.magnitude;

            // 检查是否在死区内
            if (distance < deadZoneRadius)
            {
                currentRegion = HotboxRegion.None;
                return;
            }

            // 检查是否在热盒范围内
            if (distance > hotboxRadius * 5f)
            {
                currentRegion = HotboxRegion.None;
                return;
            }

            // 计算角度 (0-360度)
            float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
            angle = (angle + 360) % 360;

            // 精确区域划分
            if (angle >= 337.5f || angle < 22.5f)
                currentRegion = HotboxRegion.Right;
            else if (angle >= 22.5f && angle < 67.5f)
                currentRegion = HotboxRegion.Focus;
            else if (angle >= 67.5f && angle < 112.5f)
                currentRegion = HotboxRegion.Bottom;
            else if (angle >= 112.5f && angle < 157.5f)
                currentRegion = HotboxRegion.Toggle2D3D;
            else if (angle >= 157.5f && angle < 202.5f)
                currentRegion = HotboxRegion.Left;
            else if (angle >= 202.5f && angle < 247.5f)
                currentRegion = HotboxRegion.Front;
            else if (angle >= 247.5f && angle < 292.5f)
                currentRegion = HotboxRegion.Top;
            else
                currentRegion = HotboxRegion.Back;
        }

        private static void ExecuteRegionAction(SceneView sceneView)
        {
            Vector3 originalPivot = sceneView.pivot;
            float originalSize = sceneView.size;

            // 退出2D模式（如果当前是2D模式且不是Focus操作）
            bool shouldExit2D = currentRegion != HotboxRegion.Focus &&
                               currentRegion != HotboxRegion.Toggle2D3D &&
                               sceneView.in2DMode;

            if (shouldExit2D)
            {
                sceneView.in2DMode = false;
                sceneView.orthographic = true; // 确保切换到正交视图
            }

            switch (currentRegion)
            {
                case HotboxRegion.Top:
                    sceneView.orthographic = true;
                    sceneView.rotation = Quaternion.Euler(90, 0, 0);
                    sceneView.pivot = originalPivot;
                    sceneView.size = originalSize;
                    break;

                case HotboxRegion.Bottom:
                    sceneView.orthographic = true;
                    sceneView.rotation = Quaternion.Euler(-90, 0, 0);
                    sceneView.pivot = originalPivot;
                    sceneView.size = originalSize;
                    break;

                case HotboxRegion.Left:
                    sceneView.orthographic = true;
                    sceneView.rotation = Quaternion.Euler(0, 90, 0);
                    sceneView.pivot = originalPivot;
                    sceneView.size = originalSize;
                    break;

                case HotboxRegion.Right:
                    sceneView.orthographic = true;
                    sceneView.rotation = Quaternion.Euler(0, -90, 0);
                    sceneView.pivot = originalPivot;
                    sceneView.size = originalSize;
                    break;

                case HotboxRegion.Front:
                    sceneView.orthographic = true;
                    sceneView.rotation = Quaternion.Euler(0, 0, 0);
                    sceneView.pivot = originalPivot;
                    sceneView.size = originalSize;
                    break;

                case HotboxRegion.Back:
                    sceneView.orthographic = true;
                    sceneView.rotation = Quaternion.Euler(0, 180, 0);
                    sceneView.pivot = originalPivot;
                    sceneView.size = originalSize;
                    break;

                case HotboxRegion.Toggle2D3D:
                    // 切换2D/3D模式
                    bool wasIn2DMode = sceneView.in2DMode;
                    sceneView.in2DMode = !sceneView.in2DMode;

                    if (wasIn2DMode) // 从2D切换到3D
                    {
                        // 切换到透视模式
                        sceneView.orthographic = false;

                        // 设置左前上方45度方位
                        sceneView.rotation = Quaternion.Euler(30, -45, 0);

                        // 保持视野不变
                        sceneView.pivot = originalPivot;
                        sceneView.size = originalSize;
                    }
                    else // 从3D切换到2D
                    {
                        sceneView.orthographic = true;
                    }
                    break;

                case HotboxRegion.Focus:
                    if (Selection.activeTransform != null)
                    {
                        sceneView.FrameSelected();
                    }
                    break;
            }

            sceneView.Repaint();

        }

        private static void CloseHotbox()
        {
            isHotboxActive = false;
            SceneView.RepaintAll();
        }

        private static void CreateTextures()
        {
            // 加载图标资源
            centerRingTexture = LoadTexture("CenterRing");
            directionArcTexture = LoadTexture("DirectionArc");
            menuBackgroundNormalTexture = LoadTexture("MenuBackgroundNormal");
            menuBackgroundHighlightTexture = LoadTexture("MenuBackgroundHighlight");
            // 如果没有加载到图标，创建备用纹理
            if (menuBackgroundNormalTexture == null)
            {
                menuBackgroundNormalTexture = new Texture2D(1, 1, TextureFormat.ARGB32, false);
                menuBackgroundNormalTexture.SetPixel(0, 0, new Color(0.2f, 0.2f, 0.2f, 0.85f));
                menuBackgroundNormalTexture.Apply();
            }

            if (menuBackgroundHighlightTexture == null)
            {
                menuBackgroundHighlightTexture = new Texture2D(1, 1, TextureFormat.ARGB32, false);
                menuBackgroundHighlightTexture.SetPixel(0, 0, new Color(0.1f, 0.4f, 0.8f, 0.95f));
                menuBackgroundHighlightTexture.Apply();
            }

            // macOS 特殊处理
            if (Application.platform == RuntimePlatform.OSXEditor)
            {
                if (centerRingTexture != null) centerRingTexture.hideFlags = HideFlags.HideAndDontSave;
                if (directionArcTexture != null) directionArcTexture.hideFlags = HideFlags.HideAndDontSave;
                if (menuBackgroundNormalTexture != null) menuBackgroundNormalTexture.hideFlags = HideFlags.HideAndDontSave;
                if (menuBackgroundHighlightTexture != null) menuBackgroundHighlightTexture.hideFlags = HideFlags.HideAndDontSave;
            }
        }

        private static Texture2D LoadTexture(string path)
        {
            return Resources.Load<Texture2D>(path);
        }

        private static void InitializeRegions()
        {
            regions = new List<HotboxRegion>
            {
                HotboxRegion.Top,
                HotboxRegion.Bottom,
                HotboxRegion.Left,
                HotboxRegion.Right,
                HotboxRegion.Front,
                HotboxRegion.Back,
                HotboxRegion.Toggle2D3D,
                HotboxRegion.Focus
            };
        }

        private static (Vector2 direction, string label) GetRegionData(HotboxRegion region, SceneView sceneView)
        {
            switch (region)
            {
                case HotboxRegion.Top:
                    return (new Vector2(0, -1), "顶视图");

                case HotboxRegion.Bottom:
                    return (new Vector2(0, 1), "底视图");

                case HotboxRegion.Left:
                    return (new Vector2(-1, 0), "左视图");

                case HotboxRegion.Right:
                    return (new Vector2(1, 0), "右视图");

                case HotboxRegion.Front:
                    return (new Vector2(-Mathf.Cos(Mathf.PI / 4), -Mathf.Sin(Mathf.PI / 4)), "前视图");

                case HotboxRegion.Back:
                    return (new Vector2(Mathf.Cos(Mathf.PI / 4), -Mathf.Sin(Mathf.PI / 4)), "后视图");

                case HotboxRegion.Toggle2D3D:
                    // 使用当前场景视图状态确定标签
                    return (new Vector2(-Mathf.Cos(Mathf.PI / 4), Mathf.Sin(Mathf.PI / 4)),
                           sceneView.in2DMode ? "3D" : "2D");

                case HotboxRegion.Focus:
                    return (new Vector2(Mathf.Cos(Mathf.PI / 4), Mathf.Sin(Mathf.PI / 4)), "聚焦");

                default:
                    return (Vector2.zero, "");
            }
        }
    }
}